import {LoadingOutlined} from '@ant-design/icons';
import {Button, message, Result} from 'antd';
import React, {useState} from 'react';
import {checkDingTalkAuthCode} from "@/pages/User/Login/components/service";
import {history, useModel} from "umi";
import {sleep} from "ahooks/es/utils/testingHelpers";
import {useLocation} from "react-router";

const DingTalkLogin: React.FC = () => {
  // 页面上的信息提示
  const [tips, setTips] = useState("请稍后，正在处理您的登录请求....")

  // 设计发送标记，避免重复发送
  const [isSend, setIsSend] = useState(false)

  // 用户初始化信息
  const { initialState, setInitialState } = useModel('@@initialState');
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();

    // 有用户信息 设置初始参数
    if (userInfo) {
      const menus = await initialState?.fetchUserMenus?.();
      await setInitialState({
        ...initialState,
        currentUser: userInfo,
        menuData: menus,
      });
    }
  };

  function text() {
    sleep(50000)

  }
  text()
  // 解析url参数
  function doLogin() {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const {search} = useLocation();
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const searchParams = React.useMemo(() => new  URLSearchParams(search), [search]);

    // 获取钉钉授权authCode
    // 1，扫码登录的授权码
    const authCode = searchParams.get("code")

    // 2， 钉钉客户端登录的授权码
    const autoCode = searchParams.get("autoCode")

    if (!isSend){
      if (authCode || autoCode){
        setIsSend(true)

        // 成功获取，将Code传到后台，让后台验证用户
        // 验证成功返回true和token
        const handleCheckCode = async (authCode: any, autoCode: any) => {
          try {
            const res = await checkDingTalkAuthCode({code: authCode, autoCode: autoCode});

            if(res && res.status === "done"){

              // 保存token
              localStorage.setItem('token', res.access);

              // 保存refresh token
              localStorage.setItem('refresh', res.refresh as string);
              await fetchUserInfo();

              // 跳转到登录前页面
              const historyPage = localStorage.getItem("loginRedirect")
              if (historyPage){
                window.location.href=historyPage
                localStorage.removeItem("loginRedirect")
              }else {
                history.push("/")
              }
            }else {
              message.error(res.message);
              setTips(res.message)
              return false;
            }
          } catch (error) {
            message.error('服务器错误！');
            setTips('服务器错误，验证失败！请联系管理员或稍后重试！')
            return false;
          }
        };

        // 调用组件，发送临时授权码到后台
        handleCheckCode(authCode, autoCode).then()
      }else {
        message.error("未获取到autoCode，请返回登录页重试！")
        setTips("未获取到autoCode，请返回登录页重试！")
      }
    }
  }
  doLogin()

  return (
    <Result
      icon={<LoadingOutlined />}
      title={tips}
      extra={
      <a href={"/login"}>
      <Button
        type="primary"

      >返回登录页</Button></a>
    }
    />
  );
};

export default DingTalkLogin;
